import childProcess = require('child_process');
import { getDirPath } from 'egret/platform/workspace/common/workspace';

/**
 * 执行命令
 * @param command 要被执行的命令
 */
export function exec(command: string, cwd: string = getDirPath()): Promise<string> {
	append(`${new Date().toLocaleTimeString()} 开始执行脚本:${command}`);
	return new Promise<string>((resolve, reject) => {
		childProcess.exec(command, { cwd, encoding: 'utf8' }, (error, stdout, stderr) => {
			if (error) {
				reject(error);
			} else if (stderr) {
				reject(stderr);
			} else {
				resolve(stdout);
			}
			append(`${new Date().toLocaleTimeString()} 脚本执行完毕: ${command}`);
		});
	});
}

/**
 * 执行命令
 * @param command 要被执行的命令
 */
export function execSync(command: string, cwd: string = getDirPath()) {
	append(`${new Date().toLocaleTimeString()} 开始执行脚本:${command}`);
	const str = childProcess.execSync(command, { cwd, encoding: 'utf8' });
	append(`${new Date().toLocaleTimeString()} 脚本执行完毕: ${command}`);
	return str;
}

function append(text: string) {
	if(_DEV) {
		global['___OutputView'] && global['___OutputView'].append(text);
	}
}

